package chapter18.practice.p18_1_1;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;

public class DirSize {
	private File file;
	public DirSize() {

	}
	public DirSize(String path) {
		this.file = new File(path);
	}
	
	/**
	 *  树结构表示文件节点,每个节点保存其大小信息.
	 * @author 黄传伟  2018年7月6日
	 *
	 */
	class FileNode{
		private File file;
		private long sizeForByte;
		private List<FileNode> sons;
		
		public FileNode(String baseDir) throws IOException {
			File baseFile = new File(baseDir);
			try {
				this.file = new File(baseFile.getCanonicalPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(!file.exists())
				throw new IllegalArgumentException("文件或目录不存在");
			
			List<String> sonList = new SortedDirList(baseDir).list();
			sons = new LinkedList<FileNode>();
			for(String sonPath: sonList) {
				String canonicalPath = new File(file, sonPath).getCanonicalPath();
				sons.add(new FileNode(canonicalPath));
			}
			
		}
		public long size() {
			if(file.isFile()) 
				sizeForByte = file.length();
			if(file.isDirectory() && file.list().length == 0)
				sizeForByte = 0L;
			
			for(FileNode son: sons)
				sizeForByte += son.size();
			
			return sizeForByte;
		}
	}

	
	
	public double caculate() throws IOException {
		long sizeByte = new FileNode(file.getCanonicalPath()).size();
		System.out.println(sizeByte);
		BigDecimal sizeMb = new BigDecimal(sizeByte).divide(new BigDecimal(1024 * 1024));
		return sizeMb.doubleValue();
	}
	


}
